from jili.core.convert import originalname,arg2argkv
class operator():
    def __init__(self,name,argkey,arg,argkv):
        if argkv:
            self.config=argkv.copy()
        else:
            self.config={}
        self.onprogress=[]
        self.input=[]
        self.output=[]
        self.nextnode=None
        self.info=dict(datasize=0,currsize=0,batchsize=0,countsize=0,algoname=name)
        self.calcmode="stream"#stream or batch
        if self.config:
            originalname(self.config)
        if arg:
            arg2argkv(arg,self.config,argkey)
    def refreshinfo(self):
        if self.input:
            a=self.input[0]
            self.info["datasize"]=len(a)
            if self.info["datasize"]>5000000:
                self.info["batchsize"]=round(self.info["datasize"]/10)
            elif self.info["datasize"]>500000:
                self.info["batchsize"]=round(self.info["datasize"]/5)
            else: 
                self.info["batchsize"]=self.info["datasize"]
    def counting(self):
        self.info["countsize"]=self.info["countsize"]+1
        self.info["currsize"]=self.info["currsize"]+1
        if self.info["countsize"]==self.info["batchsize"]:
            self.info["countsize"]=0
            self.callonprogress(self.info)
    def endcount(self):
        self.callonprogress(self.info)
    def setconfig(self,config):
        originalname(config)
        self.config.update(config)
    def restart(self):
        self.onprogress=[]
        self.input=[]
        self.output=[]
        self.nextnode=None
        self.info["datasize"]=0
        self.info["currsize"]=0
        self.info["countsize"]=0
        self.info["batchsize"]=0
    def setonprogress(self,oncall):
        if oncall not in self.onprogress:
            self.onprogress.append(oncall)
    def callonprogress(self,info):
        if self.onprogress:
            for i in self.onprogress:
                i(info)
    def addinput(self,input):
        if input not in self.input:
            self.input.append(input)
            if not isinstance(input,operator):
                self.info["datasize"]=len(input)
                if self.info["datasize"]>5000000:
                    self.info["batchsize"]=round(self.info["datasize"]/10)
                elif self.info["datasize"]>500000:
                    self.info["batchsize"]=round(self.info["datasize"]/5)
                else: 
                    self.info["batchsize"]=500000
        return self
    def getoutput(self):
        return self.output
    def setnextnode(self,next):
        self.nextnode=next
    def run(self):
        self.calcmode="batch"
        #self.nextnode.run()
    def oncalc(self):
        self.calcmode="stream"
        self.nextnode.run()
    def report(self,reporttype="html"):
        pass
        #if reporttype=="save":